#ifdef __cplusplus
extern "C"{
#endif

#include "xs_def.h"
#include "xs_system.h"
#include "xs_log.h"
#include "xs_string.h"
#include "xs_ctype.h"

static inline char *skip_token(const char *p)
{
	while(xs_isspace(*p)) p++;
	while(*p && !xs_isspace(*p)) p++;
	return (char*)p;
}
int xs_get_memory_info( void )
{
	int  len;
	int fp;
	char buffer[4096+1];
	char *p;
	long memory_all;
	long memory_free;

	fp = open("/proc/meminfo", O_RDONLY);
	len = read(fp, buffer, sizeof(buffer) - 1);
	close(fp);

	buffer[len]='\0';
	p = buffer;
	p = skip_token(p);
	memory_all = strtoul(p,&p,10);

	p = strchr(p,'\n');
	p = skip_token(p);

	memory_free = strtoul(p, &p, 10);
	return memory_free*100/memory_all;
}


int xs_get_tasks_info(void)
{
	DIR              *pDir ;
	struct dirent    *ent  ;
    int PidNumber =  0;
	char              childpath[512];
	const char *path="/proc";

	pDir = opendir(path);

	xs_memset(childpath, 0, sizeof(childpath));
	while((ent = readdir(pDir)) != NULL)
	{
		if(ent->d_type & DT_DIR)
        {
            if( xs_strcmp(ent->d_name, ".") == 0 || xs_strcmp(ent->d_name, "..") == 0 )
				continue;
            if( xs_isdigit(ent->d_name))
				PidNumber++;
		}
	}
	return PidNumber;
}

int xs_get_cpu_info (void)
{
	FILE *fd;
	float cpuSize;
	float cpuUser;
	char buff[256];
	char name[256];
	unsigned int iuser,inice,isystem,iidle;

	fd = fopen ("/proc/stat", "r");

	fgets (buff, sizeof(buff), fd);
	sscanf (buff,"%s %u %u %u %u",name,&iuser, &inice,&isystem,&iidle);
	fclose(fd);

	cpuUser = iuser + inice + isystem;
	cpuSize = cpuUser + iidle;

	return (int)(cpuUser*100/cpuSize);
}


int xs_system_test(void)
{
    int memry = xs_get_memory_info();
    int cpu = xs_get_cpu_info();
    int task = xs_get_tasks_info( );

    xs_logd("memory : %d, cpu : %d, task : %d", memry, cpu, task);
    return 0;
}

